package com.lg.cms.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lg.cms.entity.User;
import com.lg.cms.mapper.UserMapper;
import com.lg.cms.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lg.cms.vo.LayerTableVO;
import com.lg.cms.utils.Md5Util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author lg
 * @since 2020-09-21
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserMapper userMapper;

    /**
     * 分页查找用户实现类
     * @param page
     * @return
     */
    @Override
    public LayerTableVO<User> selectUserPage(Page page, String userName) {
        LayerTableVO<User> layerData=new LayerTableVO<>();
        List<User> userVos;
        QueryWrapper queryWrapper=new QueryWrapper();

        if (!StringUtils.isEmpty(userName)){
            queryWrapper.like("username",userName);
        }
        IPage<User> iPage=userMapper.selectPage(page,queryWrapper);
        userVos=iPage.getRecords();
        for (User u: userVos) {
            u.setStringId(u.getId()+"");
        }
        if (iPage.getTotal()==0) layerData.setCode(1);
        else layerData.setCode(0);
        layerData.setCount(iPage.getTotal());
        layerData.setData(userVos);
        layerData.setMsg("没有数据");


        return layerData;

    }



    /**
     * 添加用户实现类
     * @param user
     * @return
     */
    @Override
    public int addUser(User user) {

        User user1=userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername,user.getUsername()));
        int n=0;

        if (user1==null){
            user.setPassword(new Md5Util().textToMd5(user.getPassword()));
            n=userMapper.insert(user);
        }

        return n;
    }

    /**
     * 修改用户实现类
     * @param user
     * @return
     */
    @Override
    public int updateUser(User user) {
        Integer version=userMapper.selectById(user.getId()).getVersion();

//        if (user.getPassword().length()<16&&StringUtils.isEmpty(user.getPassword())) user.setPassword(Md5Util.textToMd5(user.getPassword()));

        user.setVersion(version);

        return userMapper.updateById(user);
    }

    /**
     * 批量删除用户实现类
     * @param ids
     * @return
     */
    @Override
    public int deleteUsersByIds(String ids) {
        String[] stids = ids.split(",");
        List<Long> listIds = new ArrayList<>();
        for(String str:stids){
           listIds.add(Long.parseLong(str));
        }


        return  userMapper.deleteBatchIds(listIds);
    }
}
